﻿using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using KWT.DRG_DIP.Common;

namespace KWT.DRG_DIP.API.Infrastructure
{
    public class CommonExceptionFilter : Attribute, IExceptionFilter
    {
        public void OnException(ExceptionContext context)
        {
            var ex = context.Exception;
            var st = new StackTrace(ex, true);
            string innerE;
            if (ex.InnerException != null)
                innerE = ex.InnerException.ToString();
            else
                innerE = "null";
            string exception = "===================================================" +
                "\r\n控制器:" + context.RouteData.Values["controller"].ToString() +
                "\r\n方法:" + ex.TargetSite.Name +
                "\r\n对象名称:" + ex.Source +
                "\r\n异常信息:" + ex.Message +
                "\r\n内部异常:" + innerE +
                "\r\n详细异常:" + ex.StackTrace +
                "\r\n行号:" + st.GetFrame(0).GetFileLineNumber();
            _Log.WriteError(exception);
            context.Result = new ContentResult { StatusCode = 500, ContentType = "application/json;charset=utf-8", Content = exception };
            context.ExceptionHandled = true;
        }
    }
}
